package com.yx.changdao.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yx.changdao.common.entity.SysUser;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;


/**
 * jwt 工具类
 */
public class JwtUtils {

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的签发时间
     */
    public static Date getIssuedAt(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getIssuedAt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的jwtLoad
     */
    public static JWTLoad getJwtload(String token) {
        if (token == null) {
            return null;
        }
        try {

            DecodedJWT jwt = JWT.decode(token);
            String jwtLoadJson = jwt.getClaim("jwtLoad").asString();

            return Json.fromJson(JWTLoad.class, jwtLoadJson);
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,expireTime后过期
     *
     * @param jwtLoad 用户名
     * @param time    过期时间s
     * @return 加密的token
     */
    public static String sign(JWTLoad jwtLoad, String salt, long time) {
        try {
            Date date = new Date(System.currentTimeMillis() + time * 1000);
            Algorithm algorithm = Algorithm.HMAC256(salt);
            // 附带的载荷信息
            return JWT.create()
                    .withClaim("jwtLoad", Json.toJson(jwtLoad, JsonFormat.compact()))
                    .withClaim("random_str", generateSalt())
                    .withExpiresAt(date)
                    .withIssuedAt(new Date())
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(String token) {
        Date now = Calendar.getInstance().getTime();
        DecodedJWT jwt = JWT.decode(token);
        return jwt.getExpiresAt().before(now);
    }

    /**
     * 生成随机盐,长度32位
     *
     * @return
     */
    public static String generateSalt() {
        SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();
        String hex = secureRandom.nextBytes(16).toHex();
        return hex;
    }


    /**
     * 设置 LoadJwt
     *
     * @param user
     * @return
     */
    public static JWTLoad setJwt(SysUser user) {
        // 设置JWt
        JWTLoad jwtLoad = new JWTLoad();
        jwtLoad.setUserID(user.getUserId());
        jwtLoad.setUsername(user.getUsername());
        return jwtLoad;
    }

}
